package com.mfz.common.encryption.rsa


import java.nio.file.Files
import java.nio.file.Paths
import java.security.Key
import java.security.KeyFactory
import java.security.interfaces.RSAPublicKey
import java.security.spec.X509EncodedKeySpec
import java.util.*

/**
 *
 * create by 2019-06-19.
 * @author yimin
 */

class RsaServer(bytes: ByteArray) : AbstractRsa() {
	override val key: Key
	override val keyLength: Int

	init {
		try {
			val keyFactory = KeyFactory.getInstance(RSA_ALGORITHM)

			//通过X509编码的Key指令获得公钥对象
			val x509KeySpec = X509EncodedKeySpec(bytes)
			key = keyFactory.generatePublic(x509KeySpec) as RSAPublicKey
			keyLength = key.modulus.bitLength()
		} catch (e: Exception) {
			throw RuntimeException("不支持的密钥", e)
		}

	}
}

/**
 * 从一个二进制文件当中读取客户端的密钥
 */
fun getRsaServerByFile(fileName: String): RsaServer {
	val kBytes = Files.readAllBytes(Paths.get(fileName))
	return RsaServer(kBytes)
}

/**
 * 从一个Base64字符串流当中当中读取客户端的密钥
 */
fun getRsaServerByBase64(base64Code: String): RsaServer {
	return RsaServer(Base64.getDecoder().decode(base64Code))
}